package com.zsck.zsali.base;

import com.zsck.zsali.http.ApiService;
import com.zsck.zsali.http.ApiSubscriber;
import com.zsck.zsali.http.RetrofitCilent;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class BaseModel {

    private CompositeDisposable mSubscriptions;
    protected ApiService apiService;
    protected ApiSubscriber apiSubscriber;

    public BaseModel() {
        super();
        apiService = RetrofitCilent.getApiService();
    }

    /**
     * 添加订阅
     */
    protected void addSubscription(Observable observable, ApiSubscriber apiSubscriber) {
        if (mSubscriptions == null) {
            synchronized (this) {
                if (mSubscriptions == null) {
                    mSubscriptions = new CompositeDisposable();
                }
            }
        }
        mSubscriptions
                .add((Disposable) observable.subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribeWith(apiSubscriber));

    }

    /**
     * 移除订阅
     */
    protected void onUnsubscribe() {
        if (mSubscriptions != null) {
            mSubscriptions.dispose();
            mSubscriptions = null;
        }
    }

}
